package chapter23;

import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;

import java.lang.reflect.Method;
import java.util.List;

/**
 * @author lzy
 * @version v1.0
 * Create DateTime: 2019/2/27 17:11
 */
public class AspectInterceptor implements MethodInterceptor {
    @Override
    public Object intercept(Object obj, Method method, Object[] args, MethodProxy proxy) throws Throwable {
        // 执行before方法
        List<Method> beforeMethods = CGLibContainer.getInterceptMethods(obj.getClass().getSuperclass(), InterceptorPoint.BEFOR);
        for (Method m : beforeMethods) {
            // 静态方法不需要obj
            m.invoke(null, obj, method, args);
        }

        try {
            //调用原始方法
            Object result = proxy.invokeSuper(obj, args);
            //执行after方法
            List<Method> afterMethod = CGLibContainer.getInterceptMethods(obj.getClass().getSuperclass(), InterceptorPoint.AFTER);
            for (Method m : afterMethod) {
                m.invoke(null, obj, method, args, result);
            }
            return result;
        } catch (Exception e) {
            //调用异常情况方法
            List<Method> exceptions = CGLibContainer.getInterceptMethods(obj.getClass().getSuperclass(), InterceptorPoint.EXCEPTION);
            for (Method m : exceptions) {
                m.invoke(null, obj, method, args, e);
            }
            throw new RuntimeException(e);
        }
    }
}
